<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-select v-model="searchParams.name" filterable placeholder="请选择角色" clearable style="width: 200px"
            @keyup.enter.native="handleListPage">
            <!-- <el-option label="请选择角色" value="" /> -->
            <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleName" />
          </el-select>

        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-debounce="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:role:export']">
          <el-button type="warning" icon="download" plain @click="handleExport()">导出</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:role:import']">
          <el-button type="info" icon="upload" plain @click="handleImport()">导入</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <!-- 数据表格 -->
      <el-table v-loading="loading" border :data="tableList" empty-text="暂时没有数据哟🌻"
        @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色名称" prop="name" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column label="开发注册" prop="allowRegister" :show-overflow-tooltip="true" align="center">
          <template #default="scope">
            {{
              scope.row.allowRegister ? '是' : '否'
            }}
          </template>
        </el-table-column>
        <el-table-column label="角色标识" prop="tag" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column label="用户数量" prop="userCount" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column label="权限级别" prop="level" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column label="敏感级别" prop="warnLevel" :show-overflow-tooltip="true" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="warnLevelOptions" :value="scope.row.warnLevel"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-tooltip content="查看详情" placement="top">
              <el-button type="primary" icon="View" circle plain @click="handlePerview(row)"
                v-auth="['system:role:update']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除角色" placement="top">
              <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"
                v-auth="['system:role:delete']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- {{ searchParams.page }} --- {{ searchParams.pageSize }} -->
      <!-- 分页 -->
      <el-pagination background v-model:current-page="searchParams.page" v-model:page-size="searchParams.pageSize"
        v-show="total > 0" :page-sizes="[10, 20, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleListPage" @current-change="handleListPage" />

      <!-- 添加 OR 修改 -->
      <KoiDialog ref="koiDialogRef" :title="title" @koiConfirm="handleConfirm" @koiCancel="handleCancel"
        :loading="confirmLoading">
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px">
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="form.roleName" placeholder="请输入角色名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" class="p-l-10px">
                <el-form-item label="角色标识" prop="roleCode">
                  <el-input v-model="form.roleCode" placeholder="请输入角色标识" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="角色状态" prop="roleStatus">
                  <el-select v-model="form.roleStatus" placeholder="请选择角色状态" style="width: 260px" clearable>
                    <el-option label="启用" value="0" />
                    <el-option label="停用" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" class="p-l-10px">
                <el-form-item label="角色级别" prop="sorted">
                  <el-input-number v-model="form.sorted" :min="1" :step="1" style="width: 260px" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="角色备注" prop="remark">
                  <el-input v-model="form.remark" :rows="5" type="textarea" placeholder="请输入角色备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          {{ form }}
        </template>
      </KoiDialog>

      <!-- 导入 -->
      <KoiDialog ref="koiDialogRef_import" :title="title" @koiConfirm="handleConfirm_import"
        @koiCancel="handleCancel_import" :loading="confirmLoading">
        <template #content>
          <KoiUploadFile acceptType=".json" acceptTypes="json" :isMultiple="false" :limit="1" fileSize="10"
            :fileList="fileList"></KoiUploadFile>
        </template>
      </KoiDialog>

    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="rolePage">
import { nextTick, ref, reactive, onMounted } from "vue";
// @ts-ignore
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo } from "@/utils/koi.ts";
// @ts-ignore
import { getAllRole, listPage, getById, add, update, deleteById, batchDelete, updateStatus, exportRole, importRole, deleteRole } from "@/api/system/role/index.ts";
import { useRouter } from "vue-router";

const router = useRouter();
// import { WarnLevelEnum } from "@/enums/system/role.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);

// 角色数据
const roleOptions = ref<any>([]);

// 查询参数
const searchParams = ref({
  page: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  name: "",
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    page: 1,
    pageSize: 10,
    name: "",
  };
};

/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  searchParams.value.page = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleListPage();
};

const warnLevelOptions = ref([
  {
    dictLabel: "不明确",
    dictValue: "0",
    dictTag: "primary",
    dictColor: ""
  },
  {
    dictLabel: "有敏感权限",
    dictValue: "1",
    dictTag: "warning",
    dictColor: ""
  },
  {
    dictLabel: "有敏感权限且开放注册",
    dictValue: "2",
    dictTag: "danger",
    dictColor: ""
  },
])

/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据

    function removeEmptyKeys(obj: any) {
      Object.keys(obj.value).forEach(key => {
        if (obj.value[key] === "" || obj.value[key] === null || obj.value[key] === undefined) {
          delete obj.value[key];
        }
      });
    }

    removeEmptyKeys(searchParams);

    const res: any = await getAllRole(searchParams.value);
    tableList.value = res.data;
    total.value = res.count;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  } finally {
    loading.value = false;
  }
};

const handleRolelist = async () => {

  try {
    const res: any = await getAllRole({})
    roleOptions.value = res.data.map((item: any) => {
      return {
        roleId: item.id,
        roleName: item.name
      }
    });
  } catch (error) {
    console.log(error);
    koiNoticeError("角色数据查询失败，请刷新重试");
  }

};

onMounted(() => {
  handleListPage();
  handleRolelist();
});
const ids = ref<any>([]); // 选中数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  console.log(selection);
  ids.value = selection.map((item: any) => item.id);
  console.log('ids.value', ids.value);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  router.push({
    path: "/system/role/add",
  });
};

/**导出 */
const handleExport = () => {
  koiNoticeSuccess("导出");
  exportRole({ roleIds: ids.value });
};

// 弹出框-导入
const koiDialogRef_import = ref();

// 文件列表-导入
const fileList = ref<any>([]);

// 弹出框-导入-确定
const handleConfirm_import = () => {
  let formData = new FormData();
  formData.append("roleFile", fileList.value[0]);

  importRole(formData).then(() => {
    koiNoticeSuccess("导入成功");
    koiDialogRef_import.value.koiQuickClose();
    handleListPage();
  }).catch(() => {
    koiNoticeError("导入失败");
  })
};

// 弹出框-导入-取消
const handleCancel_import = () => {
  koiDialogRef_import.value.koiClose();
};

/**导入 */
const handleImport = () => {
  koiNoticeSuccess("导入");
  koiMsgBox("请不要导入当前已经存在的角色，如有重复，请在文件中删除重复角色后导入！", undefined, '继续导入', undefined, undefined)
    .then(() => {
      title.value = "角色导入";
      koiDialogRef_import.value.koiOpen();
    })
    .catch(() => {
      koiMsgWarning("已取消");
    });
};

/** 查看详情 */
const handlePerview = (row: any) => {
  koiMsgInfo("查看详情");
  router.push({ name: "roleDetail", params: { id: row.id } });
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据🌻");
    return;
  }
  try {
    const res: any = await getById(id);
    console.log(res.data);
    form.value = res.data;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据获取失败，请刷新重试🌻");
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开弹出框
  koiDialogRef.value.koiOpen();
  koiNoticeSuccess("修改🌻");
  // 重置表单
  resetForm();
  // 标题
  title.value = "角色修改";
  const roleId = row ? row.roleId : ids.value[0];
  if (roleId == null || roleId == "") {
    koiMsgError("请选择需要修改的数据🌻");
  }
  console.log(roleId);
  // 回显数据
  handleEcho(roleId);
};

/** 添加 AND 修改弹出框 */
const koiDialogRef = ref();
// 标题
const title = ref("角色管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  roleId: "",
  roleName: "",
  roleCode: "",
  roleStatus: "",
  sorted: 1,
  remark: ""
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    roleId: "",
    roleName: "",
    roleCode: "",
    roleStatus: "",
    sorted: 1,
    remark: ""
  };
};

/** 表单规则 */
const rules = reactive({
  roleName: [{ required: true, message: "请输入角色名字", trigger: "blur" }],
  roleCode: [{ required: true, message: "请输入角色编号", trigger: "blur" }],
  roleStatus: [{ required: true, message: "请输入选择角色状态", trigger: "blur" }],
  sorted: [{ required: true, message: "请输入排序号", trigger: "blur" }]
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      // 后端API-[第一种：async await]
      // try{
      //   // 添加或者修改接口
      //   await addRole(form);
      // }catch(error){
      //    console.log(error);
      // }

      // 后端API-[第二种：then]
      // addRole(form).then(() => {
      //   // 一定是成功的
      // }).catch(error => {
      //   console.log(error);
      // })

      console.log("表单ID", form.value.roleId);
      if (form.value.roleId != null && form.value.roleId != "") {
        try {
          await update(form.value);
          koiNoticeSuccess("修改成功🌻");
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试🌻");
        }
      } else {
        try {
          await add(form.value);
          koiNoticeSuccess("添加成功🌻");
          confirmLoading.value = false;
          koiDialogRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试🌻");
        }
      }
      // let loadingTime = 1;
      // setInterval(() => {
      //   loadingTime--;
      //   if (loadingTime === 0) {
      //     koiNoticeSuccess("朕让你提交了么？信不信锤你🌻");
      //     confirmLoading.value = false;
      //     resetForm();
      //     koiDialogRef.value.koiQuickClose();
      //   }
      // }, 1000);
    } else {
      koiMsgError("验证失败，请检查填写内容🌻");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDialogRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  koiMsgBox("您确认需要删除角色名称[" + row.name + "]么？").then(async () => {
    try {
      await deleteRole(row.id)
      handleListPage();
      koiNoticeSuccess("删除成功");
    } catch (error) {
      koiNoticeError("删除失败，请刷新重试");
      handleListPage();
    }
  }).catch(() => {
    koiMsgError("已取消");
  });
};
</script>

<style lang="scss" scoped></style>
